package cn.hy.controller;

import cn.hutool.core.util.RandomUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.Set;


@RestController
@RequestMapping("/rankingList")
public class RankingListController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/randomRankingList")
    public ResponseEntity<LinkedHashMap<String,Object>> randomRankingList() {
        LinkedHashMap<String,Object> data = new LinkedHashMap<>();
        //积分排行榜
        String rankingList = "ranking_list:integral";
//        战斗力排行榜
//        String combat = "ranking_list:combat";
        //随机生成100个4位数
        for (int i = 0; i < 100; i++) {
            String score = RandomUtil.randomNumbers(4);
            stringRedisTemplate.opsForZSet().add(rankingList, "user_id" + i, Integer.parseInt(score));
        }
        // 获取前5名的value
        Set<String> reverseRange = stringRedisTemplate.opsForZSet().reverseRange(rankingList, 0, 4);
        // 获取倒数5名的value
        // Set<String> range = redisTemplate.opsForZSet().range(rankingList, 0, 4);
        reverseRange.forEach(v -> {
            //根据rankingList+value获取score
            Double score = stringRedisTemplate.opsForZSet().score(rankingList, v);
            //value和score放入JSON中
            data.put(v, score);
        });
        return ResponseEntity.ok(data);
    }

}
